package top.ffhome.blog.controller;

import java.util.List;

import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import top.ffhome.blog.entity.Label;
import top.ffhome.blog.service.LabelService;
import top.ffhome.common.result.Result;
import top.ffhome.util.bean.BeanUtil;

@CrossOrigin
@RestController
@RequestMapping("api/blog/label")
public class LabelController {
	@Autowired
	private LabelService labelService;

	@RequiresPermissions(value = { "blog:article:view", "blog:label:view" }, logical = Logical.OR)
	@GetMapping("/getTree")
	public Result getTree() {
		return Result.success(labelService.getTree());
	}

	@RequiresPermissions(value = { "blog:label:add", "blog:label:edit" }, logical = Logical.OR)
	@PostMapping(value = "/save")
	public Result save(@RequestBody Label label) {
		List<String> fields = CollUtil.newArrayList("parentId", "name", "sort");
		if (!(label.getId() == null || label.getId() == 0)) {
			fields.add("id");
			fields.add("updateTime");
		}
		BeanUtil.constraintProperties(label, fields);
		if (label.getId() == null) {
			labelService.insert(label);
		} else {
			labelService.update(label);
		}
		return Result.success();
	}

	@RequiresPermissions("blog:label:edit")
	@PostMapping(value = "/move")
	public Result move(@RequestBody Label label) {
		if (ObjectUtil.isNull(label.getId()) || ObjectUtil.isNull(label.getParentId())
				|| ObjectUtil.isNull(label.getSort())) {
			return Result.fail("参数不正确");
		}
		labelService.move(label);
		return Result.success();
	}
}
